package service.impl;

import mapper.SysUserMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import pojo.Page;
import pojo.SysUser;
import service.SysUserService;

import javax.annotation.Resource;
import java.util.List;

@Transactional(rollbackFor = {Exception.class})
@Service
public class SysUserServiceImpl implements SysUserService {

    @Resource
    private SysUserMapper sysUserMapper;
    @Override
    public SysUser login(String account, String password) {
        return sysUserMapper.login(account,password);
    }

    @Transactional(readOnly = true,propagation = Propagation.NOT_SUPPORTED)
    @Override
    public List<SysUser> selectUserList(String realName, Integer roleId, Page page) {
        int count= sysUserMapper.count(realName,roleId);
        page.setTotalCount(count);
        if (page.getCurPage()>page.getTotalPage()){
            page.setCurPage(page.getTotalPage());
        }
        if (page.getCurPage()<=0){
            page.setCurPage(1);
        }
        int pageIndex=(page.getCurPage()-1)*page.getPageSize();
        page.setList(sysUserMapper.selectUserList(realName, roleId, pageIndex,page.getPageSize()));
        return page.getList();
    }

    @Override
    public boolean getPwdTrue(SysUser sysUser, String password) {
        if (sysUser.getPassword().equals(password)){
            return true;
        }
        return false;
    }


    @Override
    public int updatePwd(SysUser sysUser, String newpassword) {
        int result=0;
        try {
            if (sysUserMapper.updatePwd(sysUser.getId(),newpassword)>0){
                result=1;
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        return result;
    }

    @Override
    public int add(SysUser sysUser) {
        int result=0;
        try {
            if (sysUserMapper.add(sysUser)>0){
                result=1;
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        return result;
    }

    @Override
    public SysUser getAccountExist(String account) {
        return sysUserMapper.getAccountExist(account);
    }
}
